package com.gin.kotlin.no_gay_alliance.fragment.main.me.item

import android.content.DialogInterface
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.widget.EditText
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.ItemArgument
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.IntRangeTextWatcher
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.ItemStoreProvider
import com.gin.nga.enums.param.ItemType
import com.gin.nga.enums.param.ItemUseArg
import com.gin.nga.enums.param.ItemUseType
import com.gin.nga.response.item.ItemInfo

class ItemStoreFragment : AbstractItemFragment() {
    override fun provider() = ItemStoreProvider.getInstance()

    override fun onClickItem(itemInfo: ItemInfo) {
        Log.i(TAG, "点击商店中的道具:  ${itemInfo.typeInfo?.name}")
        val id = itemInfo.id!!.toInt()
        val api = App.INSTANCE.ngaApi.itemApi
        when (itemInfo.type) {
            // 激活码 购买选择数量
            ItemType.ACTIVATION_CODE -> buy(id)
            // 徽章，买一个
            ItemType.MEDAL -> buy(id, 1)
            // 对人，购买1个并使用，如果参数中未提供用户id，弹窗提示输入
            ItemType.TO_USER -> obtainUserId { userId -> api.use(id, ItemUseType.BUY_AND_USE, ItemUseArg(userId)).enqueue(this) }
            // 对贴，购买1个并使用，如果参数中未提供主题id，弹窗提示输入
            ItemType.TO_REPLY -> obtainTopicId { topicId, replyId -> api.use(id, ItemUseType.BUY_AND_USE, ItemUseArg(topicId, replyId)).enqueue(this) }
            else -> handler?.toast("未开发功能")
        }
    }

    /**
     * 购买
     * @param id Long
     * @param count Int?
     */
    private fun buy(id: Int, count: Int? = null) {
        val api = App.INSTANCE.ngaApi.itemApi
        if (count != null) {
            api.buy(id, count).enqueue(this)
        } else {
            // 弹窗选择购买数量
            val editText = EditText(requireContext())
            editText.setText("1")
            editText.inputType = InputType.TYPE_CLASS_NUMBER
            editText.addTextChangedListener(IntRangeTextWatcher(editText, 1))
            AlertDialogUtils.builder(requireContext(),
                title = getString(R.string.dialog_title_select_buy_count),
                contentView = editText,
                listener = { _, which ->
                    if (which == DialogInterface.BUTTON_POSITIVE) api.buy(id, editText.text.toString().toInt()).enqueue(this@ItemStoreFragment)
                }).show()
        }
    }


    companion object {
        fun newInstance(itemArgument: ItemArgument): ItemStoreFragment {
            val args = Bundle()
            args.putParcelable(ItemArgument::class.java.simpleName, itemArgument)
            val fragment = ItemStoreFragment()
            fragment.arguments = args
            return fragment
        }
    }
}